/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import entity.News;
import model.NewsModel;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import util.SocketContentHandle;

/**
 * 
 * @author xuanhung2401
 */
public class URLService extends Thread {

	static Document doc = null;
	String url = "";
	private static NewsModel newsModel = new NewsModel();
	private static String site = "vnexpress.net";
	private static String[] splitString;

	public URLService(String url) {
		this.url = url;
		this.start();
	}

	@Override
	public void run() {
		try {
			doc = SocketContentHandle.getSiteContentBySocket(site, url);
		} catch (UnknownHostException ex) {

		} catch (IOException ex) {

		}
		Elements alllink = doc.select("a");
		ArrayList<String> listLink = new ArrayList<String>();
		for (Element e : alllink) {
			String u = e.attr("href");
			// Get link from site (have not http) length more than 4.
			if (u.matches("^((?!http).)*$") && u.split("/").length > 4) {
				String myUrl = ("http://" + site + u).toLowerCase();
				String alias = "";
				splitString = myUrl.replaceAll("http://", "").split("/");
				if (splitString.length == 6) {
					alias = splitString[5];

				}
				if (splitString.length == 7) {
					alias = splitString[6];
				}
				// check exit link with url and alias before save.
				if (!newsModel.isExits(myUrl, alias)) {
					News n = new News();
					n.setUrl(myUrl.toLowerCase());
					n.setAlias(alias);
					n.setSource(site);
					n.setSourceName("VnExpress");
					n.setComplete(false);
					newsModel.save(n);
					System.out.println("Url : " + n.getUrl() + " saved !");
				}
			}
		}
		System.out.println("FN");
	}
}
